package xiaobange.service.imp;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xiaobange.common.BaseConText;
import xiaobange.common.CustomException;
import xiaobange.entity.*;
import xiaobange.mapper.OrdersMapper;
import xiaobange.service.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrderDetailService orderDetailService;


    @Autowired
    private ShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private UserService userService;

    /**
     * 提交订单
     * @param orders
     */
    @Transactional
    @Override
    public void Submit(Orders orders) {
        //获取用户ID
        Long threadSessionID = BaseConText.getThreadSessionID();
        //查询购物车
        LambdaQueryWrapper<ShoppingCart> cartLambdaQueryWrapper = new LambdaQueryWrapper<>();
        cartLambdaQueryWrapper.eq(ShoppingCart::getUserId , threadSessionID);
        List<ShoppingCart> cartList = shoppingCartService.list();
        if (cartList == null || cartList.size() == 0){
            throw new CustomException("购物车数据为空，非法操作！");
        }
        //查询地址详细详细
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());
        if (addressBook == null){
            throw new CustomException("地址信息为空，非法操作！");
        }

        //查询用户信息
        User user = userService.getById(threadSessionID);

        //向订单表插入信息
            //1.1生成一个订单ID   这个是mybatisPlus提供的一个类
        long orderID = IdWorker.getId();
        //1.2遍历下单总金额
        /**
         * AtomicInteger：其实这个是一个原子操作，他可以保证在多线程的情况下计算不出错，如果使用普通的int类型在高并发/多线程的时候有可能会出现计算错误
         */
        AtomicInteger atomicInteger = new AtomicInteger(0);
        //1.3得到订单明细表的数据
        List<OrderDetail> detailList = cartList.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(item.getName());
            orderDetail.setImage(item.getImage());
            orderDetail.setOrderId(orderID);
            orderDetail.setDishId(item.getDishId());
            orderDetail.setSetmealId(item.getSetmealId());
            orderDetail.setDishFlavor(item.getDishFlavor());
            orderDetail.setNumber(item.getNumber());
            orderDetail.setAmount(item.getAmount());
            //可以理解为 数量*金额  在转换为int类型
            atomicInteger.addAndGet(item.getAmount().multiply(new BigDecimal(item.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());

        //1.4给订单表设置数据
        orders.setId(orderID);
        orders.setNumber(String.valueOf(orderID));
        orders.setStatus(2);
        orders.setUserId(user.getId());
        orders.setAddressBookId(orders.getAddressBookId());
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setPayMethod(2);
        orders.setAmount(new BigDecimal(atomicInteger.get()));
        orders.setPhone(addressBook.getPhone());
        orders.setAddress(addressBook.getDetail());
        orders.setUserName(user.getName() != null ? user.getName() : addressBook.getConsignee());
        orders.setConsignee(addressBook.getConsignee());

        //1.5执行添加操作
        this.save(orders);

        //2网订单明细表添加数据
        orderDetailService.saveBatch(detailList);

        //3.清空购物车数据
        shoppingCartService.remove(cartLambdaQueryWrapper);
    }


}
